package com.morimoto.healthmeter.calendar;

import org.kazzz.view.calendar.CalendarSelectionEvent;
import org.kazzz.view.calendar.CalendarView;
import org.kazzz.view.calendar.DateInfo;
import org.kazzz.view.calendar.OnCalendarSelectionListener;

import com.morimoto.healthmeter.HealthMeterActivity;
import com.morimoto.rmlib.RMLog;
import com.morimoto.rmlib.StorageManager;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class InputCalendarView extends CalendarView implements OnCalendarSelectionListener {

	private HealthMeterActivity mMain = null;
	private InputCalendarView mSelf = null;
	private Context mContext = null;
	private int mDataNum = 0;

	private boolean mIsNewData = false;
	
	private DialogInputLayout mWeightInputLayout = null;
	private DialogInputLayout mFatInputLayout = null;
	private DialogInputLayout mUserInputLayout = null;
	
	public InputCalendarView(Context context) {
		super(context);
		mContext = context;
		mSelf = this;
		mMain = (HealthMeterActivity) context;
		addOnCalendarSelectionListener(this);

		StorageManager storage = mMain.getStorage();
		mDataNum = storage.getInt("dataNum");
		
		Log.d("InputCalendarView", "Data num : " + mDataNum);
		
		//for database fix ver.02
		{
			if (!storage.isContain("db_02")) {
				int dataNum = mDataNum;
				if (dataNum > 0) {
					//search Nov. data
					for (int i = 1; i <= 30; i++) {
						String indexKey = "data_2011_11_" + i;
						if (storage.isContain(indexKey)) {
							int index = storage.getInt(indexKey);
							String dayKey = index + "_d";
							storage.addString(dayKey, "2011_11_" + i);
						}
					}
					
					//serach Dec. data
					for (int i = 1; i <= 31; i++) {
						String indexKey = "data_2011_12_" + i;
						if (storage.isContain(indexKey)) {
							int index = storage.getInt(indexKey);
							String dayKey = index + "_d";
							storage.addString(dayKey, "2011_12_" + i);
						}
					}
				}
			}
		}

		for (int i = 0; i < mDataNum; i++) {
			RMLog.print("date : " + storage.getString(i + "_d"));
		}
		//データベースの修正用orz
//		if (!storage.isContain("db_01")) {
//		if (true) {
//			float max_w = 0.0f;
//			float min_w = 0.0f;
//			float max_f = 0.0f;
//			float min_f = 0.0f;
//			float max_u = 0.0f;
//			float min_u = 0.0f;
//			if (mDataNum == 0) {
//				min_w = 500.0f;
//				min_f = 100.0f;
//				min_u = 100000.0f;
//			} else {
//				min_w = 500.0f;
//				min_f = 100.0f;
//				min_u = 100000.0f;
//			}
//			
//			int dateFirst = 1;
//			for (int i = 0; i < 35; i++) {
//				String tempDate = "data_2011_11_" + dateFirst;
//				if (storage.isContain(tempDate)) {
//					int index = storage.getInt(tempDate);
//					storage.addString("index_" + index, tempDate);
//					
//					float weight = storage.getFloat(index + "_w");
//					if (weight > max_w) {
//						max_w = weight;
//					}
//					if (weight < min_w) {
//						min_w = weight;
//					}
//					float fat = storage.getFloat(index + "_f");
//					if (fat > max_f) {
//						max_f = fat;
//					}
//					if (fat < min_f) {
//						min_f = fat;
//					}
//					float user = storage.getFloat(index + "_u");
//					if (user > max_u) {
//						max_u = user;
//					}
//					if (user < min_u) {
//						min_u = user;
//					}
//					storage.addFloat("max_w", max_w);
//					storage.addFloat("min_w", min_w);
//					storage.addFloat("max_f", max_f);
//					storage.addFloat("min_f", min_f);
//					storage.addFloat("max_u", max_u);
//					storage.addFloat("min_u", min_u);
//				}
//				dateFirst++;
//			}
//			storage.addBoolean("db_01", true);
//		}
		
		//ソート
		{
//			float[] dataString = new float[mDataNum];
//			String[] indexString = new String[mDataNum];
//			String[] dateString = new String[mDataNum];
//			for (int i = 0; i < mDataNum; i++) {
//				dataString[i] = storage.get
//			}
//			java.util.Arrays.sort(array)
		}
		
	}

	/**
	 * カレンダーがTapされた時のイベントハンドラ
	 */
	@Override
	public void onCalendarSelection(CalendarSelectionEvent event) {
		DateInfo di = event.getDateInfo();
		int year = di.getYear();
		int month = di.getMonth();
		int day = di.getDay();
		Log.d("Calendar", "year:" + year + ", month:" + month + ", day:" + day);
		
		StorageManager storage = mMain.getStorage();

		//TODO 値が入力されたらカレンダーの要素の色を変えたい
//		CalendarView cv = event.getCalendarView();
		
		showDialog(di);
	}

	/**
	 * ダイアログを表示
	 * @param dateInfo
	 */
	private void showDialog(final DateInfo dateInfo) {
		LinearLayout dialogLayout = new LinearLayout(mContext);
		dialogLayout.setOrientation(LinearLayout.VERTICAL);
		
		TextView dateText = new TextView(mContext);
		dateText.setTextSize(20.0f);
		dateText.setText(dateInfo.getYear() + "年" + dateInfo.getMonth() + "月" + dateInfo.getDay() + "日\n");
		dialogLayout.addView(dateText);
		
		mWeightInputLayout = new DialogInputLayout(mContext, "体重 : ");
		mFatInputLayout = new DialogInputLayout(mContext, "体脂肪率 : ");
		mUserInputLayout = new DialogInputLayout(mContext, "その他 : ");
	    dialogLayout.addView(mWeightInputLayout);
	    dialogLayout.addView(mFatInputLayout);
	    dialogLayout.addView(mUserInputLayout);

		String dataName = "data_" + dateInfo.getYear() + "_" + dateInfo.getMonth() + "_" + dateInfo.getDay();
		StorageManager sm = mMain.getStorage();
		if (sm.isContain(dataName)) {
			int index = sm.getInt(dataName);
			mWeightInputLayout.setValue(sm.getFloat(index + "_w"));
			mFatInputLayout.setValue(sm.getFloat(index + "_f"));
			mUserInputLayout.setValue(sm.getFloat(index + "_u"));
			mIsNewData = false;
		} else {
			mIsNewData = true;
		}

	    final AlertDialog alertDialog = new AlertDialog.Builder(mContext)
	        .setTitle("計測結果を入力")
	        .setView(dialogLayout)
	        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
	        	@Override
				public void onClick(DialogInterface dialog, int which) {
	        		float inputValWight = mWeightInputLayout.getValue();
	        		float inputValFat = mFatInputLayout.getValue();
	        		float inputValUser = mUserInputLayout.getValue();
//	        		RMLog.print("weight value : " + inputVal);
	        		
	        		String dataName = "data_" + dateInfo.getYear() + "_" + dateInfo.getMonth() + "_" + dateInfo.getDay();
	        		
	        		StorageManager sm = mMain.getStorage();
	        		
	        		int dataIndex = 0;
	        		
	        		if (!sm.isContain(dataName)) {
	        			dataIndex = mDataNum;
	        			sm.addInt(dataName, mDataNum);
	        			mDataNum++;
	        			sm.addInt("dataNum", mDataNum);
	        		} else {
	        			dataIndex = sm.getInt(dataName);
	        		}
	        		
	        		sm.addFloat(dataIndex + "_w", inputValWight);
	        		sm.addFloat(dataIndex + "_f", inputValFat);
	        		sm.addFloat(dataIndex + "_u", inputValUser);
	        		
	        		sm.addString(dataIndex + "_d", dateInfo.getYear() + "_" + dateInfo.getMonth() + "_" + dateInfo.getDay());

	        		RMLog.print("data Num : " + mDataNum);
	        		
				}
			})
	        .setNegativeButton("cancel", null)
	        .create();

	    alertDialog.show();
	}
	
	private class DialogInputLayout extends LinearLayout {

		private EditText mEditText = null;
		private boolean mIsIgnoreRetForm = false;

		public DialogInputLayout(Context context, String title) {
			super(context);
			
			if ("その他 : ".equals(title))
				mIsIgnoreRetForm = true;
			
			setOrientation(LinearLayout.HORIZONTAL);
			setGravity(Gravity.RIGHT);

			TextView titleView = new TextView(context);
			titleView.setText(title);
			titleView.setTextSize(24.0f);
			addView(titleView);
		    mEditText = new EditText(context);
		    mEditText.setLayoutParams(new LayoutParams((int) (mMain.getScreenWidth() * 0.4f), LayoutParams.WRAP_CONTENT));
		    mEditText.setInputType(InputType.TYPE_CLASS_NUMBER | (InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_MASK_FLAGS));
		    addView(mEditText);
		    
//		    editText.setOnFocusChangeListener(new OnFocusChangeListener() {
//		        @Override
//		        public void onFocusChange(View v, boolean hasFocus) {
//		            if (hasFocus) {
//		                alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//		            }
//		        }
//		    });

		}
		
		/**
		 * テキストボックスに入力された値を返す
		 * @return
		 */
		public float getValue() {
			String retStr = mEditText.getText().toString();
			if (retStr.equals("")) {
				return 0.0f;
			} else {
				float ret = Float.valueOf(retStr);
				if (mIsIgnoreRetForm) {
					return ret;
				}
				if (retStr.indexOf(".") == -1) {
					char[] retChar = retStr.toCharArray();
					retStr = "";
					for (int i = 0; i < retChar.length; i++) {
						if (i == retChar.length - 1) {
							retStr += ".";
						}
						retStr += retChar[i];
					}
					ret = Float.valueOf(retStr);
				}
				return ret;
			}
		}
		
		public void setValue(float val) {
			mEditText.setText(Float.toString(val));
		}
		
	}
}
